<template>
  <div class="app-container">
    <el-dialog
      v-model="dialogVisible"
      title="兑换码设置"
      width="24%"
      :show-close="false"
      :append-to-body="true"
      :close-on-click-modal="false"
      v-dialog-drag
    >
      <el-row :gutter="16">
        <el-col :span="11">
          <div class="redemption_code_left">
            <div v-for="(item, index) in couponsCodeList" :key="index">
              <div class="left_text">
                {{ item.code }}
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="13">
          <div class="redemption_code_right">
            <el-form
              :model="form"
              ref="formRef"
              :rules="rules"
              :hide-required-asterisk="true"
              label-width="90px"
            >
              <el-form-item label="兑换码长度" prop="len">
                <el-input v-model="form.len" clearable />
              </el-form-item>
              <el-form-item label="兑换码数量" prop="num">
                <el-input v-model="form.num" clearable />
              </el-form-item>
              <div class="form_def_text1">（此处为默认发放数量）</div>
              <div class="form_btn">
                <el-button class="form_button" type="primary" @click="handleSubmit"
                  >点击生成</el-button
                >
              </div>
              <div class="form_btn">
                <el-button class="form_button excel_btn" @click="handleExport"
                  >导出兑换码</el-button
                >
              </div>
              <div class="form_def_text2">默认文件名为“兑换码.xlsx”</div>
            </el-form>
            <div class="dialog-footer mt-4">
              <el-button type="primary" @click="handleClose">确定</el-button>
              <el-button @click="handleClose">取消</el-button>
            </div>
          </div>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { addCouponsCode } from '@/api/couponsCode/couponsCode'
import { ElMessage, FormInstance } from 'element-plus'

// 定义 emits
const emit = defineEmits(['refreshShow'])

// 定义响应式数据
const dialogVisible = ref(false)
const couponsCodeList = ref<any[]>([])
const formRef = ref<FormInstance | null>(null)

const form = reactive({
  len: 5,
  num: null as number | null,
})

const queryParams = reactive({
  batchNum: null as string | null,
})

const rules = {
  len: [{ required: true, message: '请填写兑换码长度', trigger: 'blur' }],
  num: [{ required: true, message: '请填写兑换码数量', trigger: 'blur' }],
}

// 加载数据
const init = (val: number) => {
  form.num = val
  dialogVisible.value = true
}

// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false
  emit('refreshShow', {
    type: 'exchangeSetting',
    total: form.num,
    batchNum: queryParams.batchNum,
  })
}

// 导出
const handleExport = () => {
  const date = new Date()
  // @ts-ignore
  download(
    'cj-stadium/sys/couponsCode/export',
    {
      ...queryParams,
    },
    `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日_兑换码.xlsx`,
  )
}

// 防抖函数
function debounce<F extends (...args: any[]) => any>(
  func: F,
  wait: number,
  immediate = false,
): (...args: Parameters<F>) => void {
  let timeoutId: number | undefined
  return function (this: ThisParameterType<F>, ...args: Parameters<F>) {
    const callNow = immediate && !timeoutId
    clearTimeout(timeoutId)
    timeoutId = setTimeout(() => {
      timeoutId = undefined
      if (!immediate) func.apply(this, args)
    }, wait)
    if (callNow) func.apply(this, args)
  }
}

// 提交表单
const handleSubmit = debounce(
  async () => {
    try {
      if (!formRef.value) return
      await formRef.value.validate(async (valid) => {
        if (valid) {
          try {
            const res = await addCouponsCode(form)
            ElMessage.success(res.msg)
            couponsCodeList.value = res.data.list
            queryParams.batchNum = res.data.batchNum
          } catch (e) {
            ElMessage.error((e as any)?.message || '请求失败，请稍后再试')
          }
        }
      })
    } catch (e) {
      ElMessage.error((e as any)?.message || '请求失败，请稍后再试')
    }
  },
  1000,
  true,
)

// 暴露方法给父组件
defineExpose({
  init,
})
</script>

<style scoped lang="scss">
.redemption_code_left {
  padding: 10px;
  height: 298px;
  opacity: 1;
  background: rgba(255, 255, 255, 1);
  border: 1px solid rgba(166, 166, 166, 1);
  overflow-y: auto;

  .left_text {
    font-size: 12px;
    font-weight: 400;
    color: rgba(56, 56, 56, 1);
    margin: 0 0 5px 0;
  }
}

.redemption_code_right {
  text-align: center;

  .form_def_text1 {
    margin: 0 0 10px 0;
    font-size: 10px;
    font-weight: 400;
    color: rgba(212, 48, 48, 1);
  }

  .form_def_text2 {
    font-size: 12px;
    font-weight: 400;
    color: rgba(56, 56, 56, 1);
    line-height: 18px;
  }

  .form_button {
    width: 100%;
    height: 57px;
    margin: 0 0 13px 0;
    font-size: 16px;
    &.excel_btn {
      margin-bottom: 7px;
    }
  }
  .form_btn {
    padding: 0 13px 0 8px;
  }
  .dialog-footer {
    text-align: right;
    margin-right: 13px;
  }
}
:deep(.el-dialog) {
  border-radius: 6px;
  .el-dialog__header {
    border-radius: 6px 6px 0 0;
    background: rgba(243, 244, 246, 1);
    padding: 12px 15px;
    .el-dialog__title {
      font-size: 14px;
      color: #383838;
    }
  }
  .el-dialog__body {
    padding: 8px 5px 8px 7px;
  }
  .el-form-item {
    margin-bottom: 18px;
  }
  .el-form-item__content {
    line-height: 28px;
  }
  .el-input__inner {
    height: 28px;
    line-height: 28px;
    border-radius: 4px;
  }
  .el-form-item__label {
    padding-right: 19px;
    line-height: 28px;
  }
  .el-table thead tr th.el-table__cell {
    padding: 11px 0;
    font-size: 14px;
  }
  .pagination-container {
    margin-top: 13px;
  }
}
</style>
